package com.example.labapp;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class MainActivity extends AppCompatActivity {
    TextView txtMyLog;
    Button btnLogin;
    Button btnRegister;

    TextView txtStdID,txtPasswd;
    String strStdID,strPasswd,strUserName;
    AlertDialog waitingDlg=null;

    AfterThread callbackLogin=(ErrorInf res)->{   //对登录结果进行处理
        Looper.prepare();
        waitingDlg.cancel();
        if(res.status)
        {
            Intent intent=new Intent(MainActivity.this,mainMenu.class);
            intent.putExtra("stdID",strStdID);
            intent.putExtra("userName",strUserName);
            startActivity(intent);
        }
        else
        {
            switch (res.errCode)
            {
                case 1:
                    Toast.makeText(MainActivity.this,"用户名或密码错误",Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    AlertDialog.Builder dlgBuilder=new AlertDialog.Builder(MainActivity.this);
                    dlgBuilder.setTitle("错误");
                    dlgBuilder.setMessage("登录失败\n"+res.errStr);
                    dlgBuilder.setNegativeButton("返回", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            waitingDlg.cancel();
                        }
                    });
                    waitingDlg=dlgBuilder.create();
                    waitingDlg.show();
                    break;
                case 3:
                    AlertDialog.Builder dlgBuilder2=new AlertDialog.Builder(MainActivity.this);
                    dlgBuilder2.setTitle("错误");
                    dlgBuilder2.setMessage(Html.fromHtml("从 http://121.196.234.33 下载新版本",Html.FROM_HTML_MODE_LEGACY));
                    dlgBuilder2.setCancelable(false);
                    waitingDlg=dlgBuilder2.create();
                    waitingDlg.show();
                    break;
            }
        }
        Looper.loop();
    };

    private void loginExe()  //执行登录
    {
        AlertDialog.Builder dlgBuilder=new AlertDialog.Builder(MainActivity.this);
        dlgBuilder.setTitle("处理中");
        dlgBuilder.setMessage("正在登录中,等待服务器响应");
        dlgBuilder.setCancelable(false);  //点击空白处不返回
        waitingDlg=dlgBuilder.create();
        waitingDlg.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Connection DBconn = null;
                ErrorInf resData = new ErrorInf();  //返回一个结构出去
                try {
                    Class.forName("org.mariadb.jdbc.Driver");
                    DBconn = DriverManager.getConnection("jdbc:mariadb://124.222.159.110:3306/laboratory_APP?characterEncoding=utf-8/", "labApp", "3A9PvxE");
                    Statement statement1 = DBconn.createStatement();
                    ResultSet res2=statement1.executeQuery("SELECT value FROM appInf WHERE ID=1;"); //检查更新
                    res2.next();
                    if(res2.getInt("value")>5)
                    {
                        resData.status=false;
                        resData.errCode=3;
                        resData.errStr="有新版本!!!";
                        callbackLogin.callback(resData);
                        return;
                    }
                    Statement stmt = DBconn.createStatement();
                    ResultSet res = stmt.executeQuery("select Count(StdID),StdPasswd,StdName from StudUser WHERE StdID=" + strStdID + ";");
                    res.next();  //获取第一行记录
                    if (res.getInt("Count(StdID)") == 0 || !res.getString("StdPasswd").equals(strPasswd)) {
                        resData.status = false;
                        resData.errStr = "用户名或密码错误";
                        resData.errCode = 1;
                        callbackLogin.callback(resData);
                        return;
                    }
                    strUserName=res.getString("StdName");  //获取用户名，给主菜单用
                    DBconn.close();
                } catch (SQLException | ClassNotFoundException throwables) {
                    throwables.printStackTrace();
                    resData.errStr = throwables.getMessage();
                    resData.errCode = 2;
                    resData.status = false;
                    callbackLogin.callback(resData);
                    return;
                }
                resData.status = true;
                callbackLogin.callback(resData);
            }
        }).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        setTxtMyLog();
        setBtn();

        txtStdID=findViewById(R.id.txtUserName);
        txtPasswd=findViewById(R.id.txtUserPasswd);
    }

    private void setTxtMyLog()
    {
        txtMyLog=findViewById(R.id.txtMyLog);
        String s1="<a href = 'https://gitee.com/tootDebug/LabApp'>Created By 嘟嘟</a>";
        txtMyLog.setText(Html.fromHtml(s1,Html.FROM_HTML_MODE_LEGACY));
        txtMyLog.setMovementMethod(LinkMovementMethod.getInstance());
    }


    private void setBtn()
    {
        btnLogin=findViewById(R.id.btnLogin);
        btnRegister=findViewById(R.id.btnRegister);
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this,registerAct.class);
                startActivity(intent);
            }
        });
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                strStdID=txtStdID.getText().toString();
                strPasswd=txtPasswd.getText().toString();
                final String[] LoginUsername = new String[1];
                if(strStdID.length()!=9)
                {
                    Toast.makeText(MainActivity.this,"学号必须为9位",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(strPasswd.length()==0)
                {
                    Toast.makeText(MainActivity.this,"请输入密码",Toast.LENGTH_SHORT).show();
                    return;
                }
                loginExe();
            }
        });
    }
    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            System.out.println(ex.getMessage());
        }
        return null;
    }
}